package com.hunliji.monitor.share.component.db;

import com.hunliji.common.exception.ErrorException;
import com.hunliji.monitor.share.component.db.model.DatabaseConnectProperty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 数据库连接池适配
 * @author wuchen
 */
public class DatabaseConnectionsAdapter {
    private final static Logger log = LoggerFactory.getLogger(DatabaseConnectionsAdapter.class);

    private final static String DEFAULT_DB_DRIVER = "com.mysql.jdbc.Driver";
    private final static String DEFAULT_PROTOCOL = "jdbc:mysql://";
    private final static Integer DEFAULT_PORT = 3306;
    private final static String DEFAULT_PARAM = "serverTimezone=Hongkong&useSSL=false&characterEncoding=utf8&autoReconnect=true&failOverReadOnly=false";
    private final static String DIVIDE = "/";
    private final static String QUESTION_MARK = "?";
    private final static String COLON = ":";

    public static void execute(DatabaseConnectProperty property, String sql) {

        String url = buildUrl(property);
        log.info("url:{}",url);
        try (Connection connection = DriverManager.getConnection(url, property.getUserName(), property.getPassword())) {
            Class.forName(DEFAULT_DB_DRIVER);
            if (connection.isClosed()) {
                throw new ErrorException("数据库连接初始化异常");
            }
            connection.setAutoCommit(true);
            try (PreparedStatement ps = connection.prepareStatement(sql)) {
                ps.setQueryTimeout(200);
                ps.execute();
            } catch (Exception e) {
                log.error("occur an exception: ", e);
                throw new ErrorException("执行sql语句失败: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("occur an exception: ", e);
            throw new ErrorException("执行失败: " + e.getMessage());
        }
    }

    public static ResultSet executeQuery(DatabaseConnectProperty property, String sql) {

        String url = buildUrl(property);
        log.info("url:{}",url);
        try (Connection connection = DriverManager.getConnection(url, property.getUserName(), property.getPassword())) {
            Class.forName(DEFAULT_DB_DRIVER);
            if (connection.isClosed()) {
                throw new ErrorException("数据库连接初始化异常");
            }
            connection.setAutoCommit(true);
            try (PreparedStatement ps = connection.prepareStatement(sql)) {
                ps.setQueryTimeout(200);
                ResultSet resultSet = ps.executeQuery();
                return resultSet;
            } catch (Exception e) {
                log.error("occur an exception: ", e);
                throw new ErrorException("执行sql语句失败: " + e.getMessage());
            }
        } catch (Exception e) {
            log.error("occur an exception: ", e);
            throw new ErrorException("执行失败: " + e.getMessage());
        }
    }


    private static String buildUrl(DatabaseConnectProperty property) {
        StringBuilder sb = new StringBuilder();
        sb.append(DEFAULT_PROTOCOL)
                .append(property.getHost())
                .append(COLON)
                //配置端口
                .append(DEFAULT_PORT)
                .append(DIVIDE)
                .append(property.getName())
                .append(QUESTION_MARK)
                .append(DEFAULT_PARAM);

        return sb.toString();
    }
}
